<?php
namespace  app\admin\controller;

use app\common\model\Upload as UploadModel;
use app\admin\tool\Parser;
use think\Request;

/**
 * 图片和文件的管理  如果不管理起来 这个会造成磁盘资源的浪费
 * Class Upload
 * @package app\admin\controller
 */
class Upload extends Base{

    public function index(){

        $model =  UploadModel::where([])->order('id desc')->paginate('10');
        foreach( $model as $key => $val ){
            $val['path'] = $val['url'];
        }
        $parser = new Parser();
        $this->data['model'] = $model;
        $this->data['column'] = $this->column();
        $this->data['title'] = '图片管理';
        $this->data['parser'] = $parser;

        return view('',$this->data);
    }

    /**
     * 删除图片以及文件
     * @param Request $request
     * @throws
     */
    public function delete(Request $request){
        $dir = ROOT_PATH.'public'.DS;
        $id = $request->param('id');
        $file = UploadModel::get($id);
        $file = $dir.$file['url'];
        $res = @unlink($file);
        if($res){
            UploadModel::destroy(['id'=>$id]);
            $this->success("删除成功");
        }
        $this->error("删除失败");

    }


    /**
     * 调用系统上本来已经存在的图片 节省服务器空间
     */
    public function imageList(){

        $model = UploadModel::where(['type'=>'1'])->order('add_time desc')->paginate(10);
        $this->data['model'] = $model;
        $this->data['title'] = '图片列表';
        $this->data['parser'] = new Parser();
        $this->data['column'] = [
            'origin_name' =>['name'=>'图片名称','fun'=>'text','options'=>''],
            'url'         =>['name'=>'图片地址','fun'=>'singleImage','options'=>[]],
            'add_time'    =>['name'=>'上传时间','fun'=>'datetime','options'=>['format'=>'Y-m-d H:i']],
        ];

        return view('',$this->data);
    }

    /**
     * 获取单个图片
     * @param Request $request
     */
    public function getImage(Request $request){
        $id = $request->param('id');
        $model = UploadModel::get($id);
        $this->success('获取成功','',$model);
    }

    protected function column(){
        return [
            'origin_name'=>['name'=>'文件名称','fun'=>'text','options'=>[]],
            'filename'=>['name'=>'保存名称','fun'=>'text','options'=>[]],
            'path'=>['name'=>'路径','fun'=>'text','options'=>[]],
            'url'=>['name'=>'内容','fun'=>'singleImage','options'=>['style'=>'width:50px;height:50px;']],
            'ext'=>['name'=>'扩展名','fun'=>'text','options'=>[]],
            'type'=>['name'=>'类型','fun'=>'translate','options'=>['map'=>['1'=>'图片']]],
            'add_time'=>['name'=>'上传时间','fun'=>'datetime','options'=>[]],
            'size'=>['name'=>'文件大小','fun'=>'text','options'=>[]],
        ];
    }

}